package com.base.look.act;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Toast;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.base.commonlib.base.CBaseBarMvpActivity;
import com.base.commonlib.utils.PbMsgDialog;
import com.base.commonlib.utils.RxBus2;
import com.base.commonlib.widget.RightDrawEditText;
import com.base.look.R;
import com.base.look.adapter.SearchLocationAdapter;
import com.base.look.bean.LocationCheckedEntity;
import com.base.look.bean.LocationInfo;
import com.base.look.databinding.ActivitySearchLocationBinding;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Route(path = "/look/location_poi")
public class SearchLocationActivity extends CBaseBarMvpActivity implements LocationSource, AMapLocationListener, PoiSearch.OnPoiSearchListener {
    //AMap是地图对象
    private AMap aMap;
    //声明AMapLocationClient类对象，定位发起端
    private AMapLocationClient mLocationClient = null;
    //声明mLocationOption对象，定位参数
    public AMapLocationClientOption mLocationOption = null;
    //声明mListener对象，定位监听器
    private OnLocationChangedListener mListener = null;
    //标识，用于判断是否只显示一次定位信息和用户重新定位
    private boolean isFirstLoc = true;
    //private SearchLocationRecyclerAdapter mAdapter;
    private List<LocationInfo> mList = new ArrayList<>();
    private ActivitySearchLocationBinding mBinding;
    private PbMsgDialog pbMsgDialog;
    private SearchLocationAdapter searchLocationAdapter;
    //private BaseAdapter<LocationInfo> mBaseAdapter;

    @Override
    protected void init() {
        super.init();
        mBinding = (ActivitySearchLocationBinding) mRootBinding;
    }

    @Override
    protected void start() {
        setBackNavigation();
        setBarTitle("所在位置");
        if (pbMsgDialog == null) {
            pbMsgDialog = new PbMsgDialog(SearchLocationActivity.this, "正在获取地址");
        }
//        setRigImg(R.drawable.ic_main_search, new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//
//            }
//        });


        //在activity执行onCreate时执行mMapView.onCreate(savedInstanceState)，实现地图生命周期管理
        //mapView.onCreate(savedInstanceState);
        if (aMap == null) {
            aMap = mBinding.map.getMap();
            //设置显示定位按钮 并且可以点击
            UiSettings settings = aMap.getUiSettings();
            aMap.setLocationSource(this);//设置了定位的监听
            // 是否显示定位按钮
            settings.setMyLocationButtonEnabled(true);
            aMap.setMyLocationEnabled(true);//显示定位层并且可以触发定位,默认是flase
        }
        //开始定位
        pbMsgDialog.show();
        location();
        setMapListener();
        setShowList();
    }

    /**
     * 地图滑动监听
     */
    public void setMapListener() {
        aMap.setOnCameraChangeListener(new AMap.OnCameraChangeListener() {
            @Override
            public void onCameraChange(CameraPosition cameraPosition) {

            }

            @Override
            public void onCameraChangeFinish(CameraPosition cameraPosition) {
                Log.e("fanhuionFinish", "\n纬度" + cameraPosition.target.latitude
                        + "\n经度" + cameraPosition.target.longitude
                        + "\n" + cameraPosition.toString());
                wei = cameraPosition.target.latitude;
                jing =  cameraPosition.target.longitude;
                setSearchApi(cameraPosition.target.latitude, cameraPosition.target.longitude,"");
            }
        });
    }


    /**
     * 显示周边街道列表
     */
    public void setShowList() {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(SearchLocationActivity.this);
        mBinding.recyclerview.setLayoutManager(linearLayoutManager);

        searchLocationAdapter= new SearchLocationAdapter(mContext,SearchLocationActivity.this,mList);
        searchLocationAdapter.isHead(0);
//        mAdapter = new SearchLocationRecyclerAdapter(mContext,mList, SearchLocationActivity.this, true) {
//
//            @Override
//            public void convert(BaseHolder holder, final LocationInfo bean, boolean isHeader, boolean isBottom) {
//                TextView address = holder.getView(R.id.address);
//                TextView name = holder.getView(R.id.name);
//                address.setText(bean.getAddress2());
//                name.setText(bean.getName());
//            }
//        };
//        //mAdapter.addHeader(R.layout.header_search_location);
//        mAdapter.putNormalType(R.layout.item_location_result);
//        mAdapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener() {
//            @Override
//            public void onItemClick(BaseHolder holder, int dataPosition, boolean isHeader, boolean isBottom) {
////                Toast.makeText(SearchLocationActivity.this, "\n地址" + mList.get(dataPosition).getAddress()
////                        + "\n纬度" + mList.get(dataPosition).getLatitude()
////                        + "\n经度" + mList.get(dataPosition).getLonTitude(), Toast.LENGTH_SHORT).show();
//                LocationCheckedEntity locationCheckedEntity=new LocationCheckedEntity();
//                locationCheckedEntity.setAddress(mList.get(dataPosition).getName());
//                locationCheckedEntity.setLatitude(mList.get(dataPosition).getLatitude());
//                locationCheckedEntity.setLonTitude(mList.get(dataPosition).getLonTitude());
//                locationCheckedEntity.setState(0x00000101);
//                RxBus2.getInstance().post(locationCheckedEntity);
//                finish();
////            }
//            }
//        });
        mBinding.recyclerview.setAdapter(searchLocationAdapter);
        //setHeaderView(mBinding.recyclerview);
//        mBinding.recyclerview.addItemDecoration(new RecyclerViewSpacesItemDecoration
//                (10, 10, 10, 10));
//        myAdapter.setOnItemClickListener(new MyAdapter.OnItemClickListener() {
//            @Override
//            public void onClick(int position) {
//                Toast.makeText(SearchLocationActivity.this, "\n地址" + mList.get(position).getAddress()
//                        + "\n纬度" + mList.get(position).getLatitude()
//                        + "\n经度" + mList.get(position).getLonTitude(), Toast.LENGTH_SHORT).show();
//            }
//        });
    }

    Double wei;
    Double jing;
    int page = 1;

    /**
     * 检索
     */
    public void setSearchApi(Double wei, Double jing,String keyword) {
        mList.clear();
        searchLocationAdapter.notifyDataSetChanged();
        PoiSearch.Query query = new PoiSearch.Query(keyword, "", "");
        query.setPageSize(100);
        query.setPageNum(page);
        PoiSearch search = new PoiSearch(this, query);
        search.setBound(new PoiSearch.SearchBound(new LatLonPoint(wei, jing), 1000));
        search.setOnPoiSearchListener(this);
        search.searchPOIAsyn();
        //up
    }

    private void location() {
        //初始化定位
        mLocationClient = new AMapLocationClient(getApplicationContext());
        //设置定位回调监听
        mLocationClient.setLocationListener(this);
        //初始化定位参数
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为Hight_Accuracy高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);
        //设置是否只定位一次,默认为false
        mLocationOption.setOnceLocation(false);
        //设置是否强制刷新WIFI，默认为强制刷新
        mLocationOption.setWifiActiveScan(true);
        //设置是否允许模拟位置,默认为false，不允许模拟位置
        mLocationOption.setMockEnable(false);
        //设置定位间隔,单位毫秒,默认为2000ms
        mLocationOption.setInterval(2000);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        mLocationClient.startLocation();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
        mBinding.map.onDestroy();
        mLocationClient.stopLocation();//停止定位
        mLocationClient.onDestroy();//销毁定位客户端。

    }

    @Override
    protected int getLayoutResource() {
        return R.layout.activity_search_location;
    }

    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView.onResume ()，实现地图生命周期管理
        mBinding.map.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView.onPause ()，实现地图生命周期管理
        mBinding.map.onPause();
    }


    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，实现地图生命周期管理
        mBinding.map.onSaveInstanceState(outState);
    }


    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (aMapLocation != null) {
            if (aMapLocation.getErrorCode() == 0) {
                //定位成功回调信息，设置相关消息
                aMapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见官方定位类型表
                aMapLocation.getLatitude();//获取纬度
                aMapLocation.getLongitude();//获取经度
                aMapLocation.getAccuracy();//获取精度信息
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date date = new Date(aMapLocation.getTime());
                df.format(date);//定位时间
                aMapLocation.getAddress();//地址，如果option中设置isNeedAddress为false，则没有此结果，网络定位结果中会有地址信息，GPS定位不返回地址信息。
                aMapLocation.getCountry();//国家信息
                aMapLocation.getProvince();//省信息
                aMapLocation.getCity();//城市信息
                aMapLocation.getDistrict();//城区信息
                aMapLocation.getStreet();//街道信息
                aMapLocation.getStreetNum();//街道门牌号信息
                aMapLocation.getCityCode();//城市编码
                aMapLocation.getAdCode();//地区编码
                mBinding.search.setOnTextChangedListener(new RightDrawEditText.OnTextChangedListener() {
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                    }

                    @Override
                    public void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) {
                            setSearchApi(wei,jing,text.toString());
                    }

                    @Override
                    public void afterTextChanged(Editable s) {

                    }
                });
                // 如果不设置标志位，此时再拖动地图时，它会不断将地图移动到当前的位置
                if (isFirstLoc) {
                    wei = aMapLocation.getLatitude();
                    jing =  aMapLocation.getLongitude();
                    setSearchApi(aMapLocation.getLatitude(), aMapLocation.getLongitude(),"");
                    //设置缩放级别
                    aMap.moveCamera(CameraUpdateFactory.zoomTo(17));
                    //将地图移动到定位点
                    aMap.moveCamera(CameraUpdateFactory.changeLatLng(new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude())));
                    //点击定位按钮 能够将地图的中心移动到定位点
                    mListener.onLocationChanged(aMapLocation);
                    //添加图钉
//                      aMap.addMarker(getMarkerOptions(amapLocation));
                    //获取定位信息
                    StringBuffer buffer = new StringBuffer();
                    buffer.append(aMapLocation.getCountry() + ""
                            + aMapLocation.getProvince() + ""
                            + aMapLocation.getCity() + ""
                            + aMapLocation.getProvince() + ""
                            + aMapLocation.getDistrict() + ""
                            + aMapLocation.getStreet() + ""
                            + aMapLocation.getStreetNum());
                    //Toast.makeText(getApplicationContext(), buffer.toString(), Toast.LENGTH_LONG).show();
                    isFirstLoc = false;
                }
            } else {
                //显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
                Log.e("AmapError", "location Error, ErrCode:"
                        + aMapLocation.getErrorCode() + ", errInfo:"
                        + aMapLocation.getErrorInfo());
                Toast.makeText(getApplicationContext(), "定位失败", Toast.LENGTH_LONG).show();
            }
        }

    }

    @Override
    public void activate(OnLocationChangedListener onLocationChangedListener) {
        mListener = onLocationChangedListener;
    }

    @Override
    public void deactivate() {
        mListener = null;
    }

    @Override
    public void onPoiSearched(PoiResult result, int i) {
        PoiSearch.Query query = result.getQuery();

        ArrayList<PoiItem> pois = result.getPois();
        for (PoiItem poi : pois) {
            Log.e("fanhuidepois",
                    "\ngetAdCode" + poi.getAdCode() +
                            "\ngetAdName" + poi.getAdName() +
                            "\ngetBusinessArea" + poi.getBusinessArea() +
                            "\ngetCityCode" + poi.getCityCode() +
                            "\ngetCityName" + poi.getCityName() +
                            "\ngetDirection" + poi.getDirection() +
                            "\ngetEmail" + poi.getEmail() +
                            "\ngetParkingType" + poi.getParkingType() +
                            "\ngetPoiId" + poi.getPoiId() +
                            "\ngetPostcode" + poi.getPostcode() +
                            "\ngetProvinceCode" + poi.getProvinceCode() +
                            "\ngetProvinceName" + poi.getProvinceName() +
                            "\ngetShopID" + poi.getShopID() +
                            "\ngetSnippet" + poi.getSnippet() +
                            "\ngetTel" + poi.getTel() +
                            "\ngetTitle" + poi.getTitle() +
                            "\ngetTypeCode" + poi.getTypeCode() +
                            "\ngetTypeDes" + poi.getTypeDes() +
                            "\ngetWebsite" + poi.getWebsite() +
                            "\ngetDistance" + poi.getDistance() +
                            "\ngetEnter" + poi.getEnter() +
                            "\ngetExit" + poi.getExit() +
                            "\ngetIndoorData" + poi.getIndoorData() +
                            "\ngetLatLonPoint" + poi.getLatLonPoint() +
                            "\ngetPhotos" + poi.getPhotos() +
                            "\ngetPoiExtension" + poi.getPoiExtension() +
                            "\ngetSubPois" + poi.getSubPois() +
                            "\n");
            String name = poi.getCityName();//北京市
            String city = poi.getAdName();//海淀区
            String area = poi.getBusinessArea();//清河
            String snippet = poi.getSnippet();//街道地址
            String detail = poi.getTitle();
            LocationInfo info = new LocationInfo();
            info.setAddress(detail);
            info.setAddress2(name + city + area + snippet);
            info.setName(poi.getTitle());
            LatLonPoint point = poi.getLatLonPoint();
            info.setLatitude(point.getLatitude());
            info.setLonTitude(point.getLongitude());
            mList.add(info);
        }
        pbMsgDialog.hide();
        searchLocationAdapter.notifyDataSetChanged();
    }

    @Override
    public void onPoiItemSearched(PoiItem poiItem, int i) {

    }
}
